package com.fzy.common.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

public class URLFilter implements Filter {

    private static String web_xml_url;

    private static String forward;

    /**
     * URL过滤,true为合法 false为非法
     *
     * @return
     */
    public static boolean UrlFile(HttpServletRequest request) {

        //转义字符
        String web_xml[] = web_xml_url.split("\\|");
        StringBuffer str;
        String st[];
        StringBuffer keyName;
        Enumeration enu = request.getParameterNames();

        while (enu.hasMoreElements()) {
            keyName = new StringBuffer((String) enu.nextElement());


            if (request.getParameter(keyName.toString()) != null) {
                str = new StringBuffer(request.getParameter(keyName.toString()));


                for (int i1 = 0; i1 < web_xml.length; i1++) {

                    if (str.lastIndexOf(web_xml[i1]) != -1) {

                        return false;
                    }
                }

            } else if (request.getParameterValues(keyName.toString()) != null) {
                st = request.getParameterValues(keyName.toString());
                for (int i = 0; i < st.length; i++) {
                    for (int j = 0; j < web_xml.length; j++) {
                        if (st[i].lastIndexOf(web_xml[j]) != -1) {
                            return false;
                        }
                    }
                }

            }
        }

        return true;

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {


        boolean boo = URLFilter.UrlFile((HttpServletRequest) request);


        if (boo == false) {

            request.getRequestDispatcher(forward).forward(request, response);

        } else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        URLFilter.web_xml_url = filterConfig.getInitParameter("sql");
        URLFilter.forward = filterConfig.getInitParameter("forward");
        System.out.println(web_xml_url);

    }


    public static String getWeb_xml_url() {

        return web_xml_url;
    }

    public static void setWeb_xml_url(String web_xml_url) {
        URLFilter.web_xml_url = web_xml_url;
    }

    public static String getForward() {
        return forward;
    }

    public static void setForward(String forward) {
        URLFilter.forward = forward;
    }


}